/* eslint-disable array-callback-return */
/* eslint-disable default-case */
import { message, Modal } from 'antd';
import * as service from '@/services/socket';
import {
  getProType,
  getDictCode,
  getProList,
  uploadFile,
  getDetail,
  addProbFdbk,
  cancelSign,
  addProbPopupView,
  addProb,
} from '@/services/problem';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

const namespace = 'problempage';
export default {
  namespace,
  state: {
    proPageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proFormFieldsValue: {},
    resultInfo: {
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    probTypeList: [],
    proObjList: [],
    alrtObjsList: [],
    proDetail: {},
    visible: false,
    btnFlag: false,
  },
  effects: {
    // 列表查询
    getProList: [
      function*({ payload }, { call, put }) {
        const res = yield call(getProList, payload);
        const {
          pageArg: { currentPage, pageSize },
        } = payload;
        if (res.success) {
          yield put({
            type: 'updateProList',
            payload: {
              data: res.data,
              currentPage,
              pageSize,
            },
          });
        } else {
          message.warning(res.message);
        }
      },
      { type: 'takeLatest' },
    ],
    // 标记问题人员
    *addProb({ payload, callback }, { call, put }) {
      const response = yield call(addProb, payload);
      if (response.success) {
        if (!response.data) {
          message.success('标记成功');
          yield put({
            type: 'updateModalData',
            payload: { visible: false },
          });
        } else if (response.data.success) {
          Modal.warning({
            title: '标记成功',
            content: response.data.msg,
            okText: '关闭',
            okType: 'default',
            autoFocusButton: 'cancel',
            onOk: () => {
              if (callback) callback(response);
            },
          });
          yield put({
            type: 'updateModalData',
            payload: { visible: false },
          });
        } else if (!response.data.success) {
          Modal.error({
            title: '标记失败',
            content: response.data.msg,
            okText: '关闭',
            okType: 'default',
            autoFocusButton: 'cancel',
            onOk: () => {
              if (callback) callback(response);
            },
          });
          yield put({
            type: 'updateModalData',
            payload: { visible: false },
          });
        }
      } else {
        yield put({
          type: 'updateModalData',
          payload: { visible: false },
        });
        Modal.error({
          title: '标记失败',
          content: response.message,
          okText: '关闭',
          okType: 'default',
          autoFocusButton: 'cancel',
        });
      }
      return response;
    },
    // 获取详情
    *getDetail({ payload }, { call, put }) {
      const res = yield call(getDetail, payload);
      if (res.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            proDetail: res.data,
          },
        });
      } else {
        yield put({
          type: 'updateModalData',
          payload: {
            btnFlag: true,
          },
        });
        message.warning(res.message || '服务端错误');
      }
    },
    // 获取标记问题人员弹框数据
    *addProbPopupView({ payload }, { call, put }) {
      const res = yield call(addProbPopupView, payload);
      if (res.success) {
        yield put({
          type: 'updateModalData',
          payload: {
            proObjList: res.data.probObjs || [],
            probTypeList: res.data.probTypes || [],
            alrtObjsList: res.data.alrtObjs || [],
            visible: true,
          },
        });
      } else {
        message.warning(res.message || '服务端错误');
      }
    },
    // 反馈
    *addProbFdbk({ payload }, { call }) {
      const res = yield call(addProbFdbk, payload);
      if (res.success) {
        message.success('操作成功');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },
    // 取消
    *cancelSign({ payload }, { call }) {
      const res = yield call(cancelSign, payload);
      if (res.success) {
        message.success('操作成功');
      } else {
        message.warning(res.message || '服务端错误');
      }
      return res;
    },

    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        const response = yield call(uploadFile, payload);
        if (response.success) {
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: response.data,
            });
          }
        } else {
          // 上传失败
          message.warning(`${response.message || '操作失败：服务端错误'}`);
        }
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s[namespace]);
      let { showProgress, resultInfo, currentStep } = state;
      const { busiType } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchNo: payload.batchId,
          busiType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 获取问题人员类型
    *fetchProType({ payload }, { call, put }) {
      const response = yield call(getProType, payload);
      if (response.success) {
        yield put({
          type: 'getProType',
          payload: {
            data: response.data,
          },
        });
      }
    },
    // 获取提醒对象
    *fetchAlertList({ payload }, { call, put }) {
      const response = yield call(getDictCode, payload);
      if (response.success) {
        yield put({
          type: 'getAlertList',
          payload: {
            data: response.data,
          },
        });
      }
    },
    // 获取问题对象
    *fetchProObjList({ payload }, { call, put }) {
      const response = yield call(getDictCode, payload);
      if (response.success) {
        yield put({
          type: 'getProObjList',
          payload: {
            data: response.data,
          },
        });
      }
    },
  },
  reducers: {
    // 更改问题人员列表
    updateProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = data.pageRecords && Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        proPageData: {
          list,
          pagination: { total: data.totalCount || 0, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModalData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取问题人员类型
    getProType(state, { payload }) {
      const probTypeList = payload.data;
      return {
        ...state,
        probTypeList,
      };
    },
    // 获取提醒对象
    getAlertList(
      state,
      {
        payload: { data },
      }
    ) {
      const tempArr = [];
      data.ALRT_OBJ.map(item => {
        tempArr.push({ label: item.itemName, value: item.itemCode });
      });
      return {
        ...state,
        alertObjList: tempArr,
      };
    },
    // 获取问题对象
    getProObjList(state, { payload }) {
      const tempArr = [];
      const listArr = [...payload.data.BIZ_INS_TYPE, ...payload.data.BIZ_ACCU_TYPE];
      listArr.map(item => {
        tempArr.push({ label: item.itemName, value: item.itemCode });
      });
      return {
        ...state,
        proObjList: tempArr,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
